package com.lagou.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lcy
 * @description TODO
 * @date 2020/11/12 21:33
 * @vserion 1.3.3
 */
@Activate(group = CommonConstants.CONSUMER)
public class ApmFilter implements Filter {
	private static   List<Integer> list = new ArrayList<>();

	private static  HashMap<String,List<Integer>> map = new HashMap<String,  List<Integer>>();

	private static ConcurrentHashMap<String,CountData> m = new ConcurrentHashMap<>();

	private static long upPrintTime=0;

	private static long timeOut=0;
	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
		// 开始时间
		long startTime = System.currentTimeMillis();
		Result invoke = invoker.invoke(invocation);

		// 获取方法名称
		String methodName = invocation.getMethodName();
		CountData countData= m.get(methodName);
		if(countData==null){
			countData= CountData.getInstance();
		}
		m.put(methodName,countData);
		long endTime = System.currentTimeMillis();


		Long resultTime = endTime - startTime;
		int intValue = resultTime.intValue();
		//添加请求次数、耗时
		countData.addTimesNum(intValue);

//		//每五秒打印一次
		if(upPrintTime==0 || System.currentTimeMillis()-upPrintTime>=5000) {
			upPrintTime=System.currentTimeMillis();
			//统计TP90
			int tp90 = countData.statTP(0.9F);
			//统计TP95
			int tp95 = countData.statTP(0.95F);

			System.out.println("__________IP:" + RpcContext.getContext().getRemoteHost()
					+ ", 方法名称:" + invocation.getMethodName()
					+ ", 请求次数: " + countData.getTotalTimes() + " "
					+ ", TP90: " + tp90 + "ms "
					+ ", TP95: " + tp95 + "ms "
			);
		}
		return invoke;
	}

}
